﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.IO;
using System.Net;

using ZD_Domain;
using ZD_Utility;
using ZD_Utility.ZD_Common;
using ZD_Utility.ZD_WebRequest;

namespace ZD_MVC
{
    /// <summary>
    /// CollectionImage 的摘要说明
    /// </summary>
    public class CollectionImage : AJAXHandlerBase
    {

        public override void AJAXHandler()
        {
            if (Request["sUrl"].IsNullOrEmpty() ||
                Request["w"].IsNullOrEmpty() ||
                Request["h"].IsNullOrEmpty() ||
                Request["jsoncallback"].IsNullOrEmpty())
                return;

            tb_ImageInfo imgModel = new tb_ImageInfo
            {
                SourceUrl = Request["sUrl"],
                Width = Request["w"].ToInt(),
                Height = Request["h"].ToInt(),
                Description = Request["des"]
            };

            ZDRequestBase request = new ZDRequestBase(imgModel.SourceUrl);
            request.req.Referer = Request.UrlReferrer.ToString();
            request.req.UserAgent = Request.UserAgent;
            CookieContainer cookieContainer = new CookieContainer();

            if (Request.Cookies.Count > 0)
            {
                foreach (Cookie item in Request.Cookies)
                {
                    cookieContainer.Add(item);
                }
                request.req.CookieContainer = cookieContainer;
            }

            WebResponse response = request.SendRequest();
            Stream imgStream = response.GetResponseStream();
            if (imgStream != null)
            {
                string imgFormat = GetImageFormat(response.ContentType);
                string path = Request.MapPath("/Images/" + Guid.NewGuid().ToString()) + imgFormat;
                FileStream imgFile = File.Create(path);
                int readCounts = 0;//实际读取自己数
                byte[] buffer = new byte[32 * 1024];
                do
                {
                    readCounts = imgStream.Read(buffer, 0, buffer.Length);
                    imgFile.Write(buffer, 0, readCounts);
                }
                while (readCounts > 0);
                Image img = Image.FromStream(imgFile);
                WriteAsCrossDomain(Request["jsoncallback"], string.Format("'宽：{0}，高：{1}'", img.Width, img.Height));
                imgFile.Close();
                imgStream.Close();
                response.Close();
            }

        }


        /// <summary>
        /// 根据WebResponse.ContentType 是否为图片文件
        /// </summary>
        /// <returns></returns>
        public bool ValidateImage(string contentType)
        {
            if (contentType.IsNullOrEmpty())
                return false;

            if (contentType.IndexOf("image/") == 0)
                return true;
            return false;
        }


        /// <summary>
        /// 根据ContentType 获取图片格式
        /// </summary>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public string GetImageFormat(string contentType)
        {
            string format = string.Empty;
            if (!ValidateImage(contentType))
                return format;

            format = "." + contentType.Substring(contentType.IndexOf("/") + 1).ToLower();

            if (format == "jpeg")
                format = ".jpg";

            return format;
        }

    }
}